package com.example.simplerpc.client.discover;

import com.alibaba.fastjson.JSON;
import com.example.simplerpc.common.serializer.ZookeeperSerializer;
import com.example.simplerpc.common.service.Service;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname: ZookeeperServiceDiscover
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/12/18 16:08
 */
public class ZookeeperServiceDiscover implements ServiceDiscover {
    private ZkClient zkClient;
    public ZookeeperServiceDiscover(String address){
        zkClient = new ZkClient(address);
        zkClient.setZkSerializer(new ZookeeperSerializer());
    }

    /**
     *  获取服务列表
     * @param name  服务名
     * @return  服务列表
     */
    @Override
    public List<Service> getServices(String name) {
        String path = "/simpleRpc/"+name+"/service";
        List<String> children = zkClient.getChildren(path);
        List<Service> services = children.stream().map(str -> {
            String deCh = null;
            try {
                deCh = URLDecoder.decode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return JSON.parseObject(deCh, Service.class);
        }).collect(Collectors.toList());
        return services;
    }
}
